import { messages, deepCopy } from 'share/common';
import React from 'react'
import { connect } from 'react-redux'
import { Button, Badge, Popover, Icon, Modal, Tooltip, Alert, Menu, Dropdown, message, Spin } from 'antd'
import SlideFrame from 'components/slide-frame'
import expenseStandardService from 'containers/expense-reimbursement-control/expense-standard/expense-standard.service'
import 'styles/setting/expense-type/new-expense-type/expense-type-standard.scss'
import constants from 'share/constants'
import NewRule from 'containers/expense-reimbursement-control/expense-standard/reimbursement-standard/new-rule'
import NewExpenseTypeRule from 'containers/expense-reimbursement-control/expense-standard/reimbursement-standard/new-expense-type-rule'
const confirm = Modal.confirm;
import moment from 'moment'
import errorMessage from 'share/errorMessage'
import ResizeTable from "components/resize-table";
import Condition from 'components/condition'
const { If } = Condition;

class ExpenseTypeStandard extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      saving: false,
      rules: [],
      loading: false,
      nowRule: {},
      nowEditRule: {},
      showSlideFrame: false,
      showRuleSlideFrame: false,
      nowCondition: {},
      pullData: [],
      itemData: [],
      copy: false,
      ruleLoading: false,
      columns: [
        {title: messages('setting.key1530')/*管控项*/, dataIndex: 'messageKey', render: this.getMessageKey},
        {title: messages('setting.key1531')/*取值方式*/, dataIndex: 'restriction',
          render: restriction => constants.getTextByValue(restriction, 'restrictions')},
        {title: messages('setting.key1536')/*条件内容*/, dataIndex: 'ruleContent', render: this.renderRuleContent},
        {title: messages('setting.key1147')/*操作*/, dataIndex: 'operate', render: (text, record) => this.renderOperate(text, record)
        }
      ]
    }
  }

  componentWillMount(){
    this.getRules(this.getData);
  }

  componentDidMount(){}

  getRules = callBack => {
    const { expenseType, expenseTypeSetOfBooks: { id } } = this.props;
    const { nowRule } = this.state;
    this.setState({ ruleLoading: true });
    expenseStandardService.getRules(expenseType.expenseTypeOID, id).then(res => {
      res.data.map((item, index) => item.index = index + 1);
      this.setState({
        rules: res.data,
        ruleLoading: false
      }, () => {
        if(res.data.length > 0 && (!nowRule.ruleOID || res.data.filter(item => item.ruleOID === nowRule.ruleOID).length === 0)){
          this.setState({ nowRule: res.data[0] }, () => {
            if(callBack) callBack();
          });
        } else if(res.data.length === 0){
          this.setState({ nowRule: {} }, () => {
            if(callBack) callBack();
          })
        }
      })
    })
  };

  getData = callBack => {
    let { nowRule, pullData } = this.state;
    if(nowRule.ruleOID){
      this.setState({ loading: true });
      expenseStandardService.getConditions(nowRule.ruleOID).then(res => {
        let resData = res.data;
        const { language } = this.props;
        let services = [];
        let itemData = [];
        const isAll = res.data.source === 1001;
        resData.conditions.map((item, index) => {
          if(item.ruleContent){
            if(item.ruleDataType === 'COST_DEPARTMENT'){
              itemData.push({
                index,
                key: 'departmentOID',
                label: 'path'
              });
              services.push(expenseStandardService.getDepartment(isAll));
            }
            if(item.ruleDataType === 'COST_CENTER'){
              itemData.push({
                index,
                key: 'id',
                label: 'name'
              });
              services.push(expenseStandardService.getCostCenterItems(item.messageKey))
            }
            if(item.ruleDataType === 'USER_GROUP'){
              itemData.push({
                index,
                key: 'id',
                label: 'name'
              });
              services.push(expenseStandardService.getUserGroup(isAll))
            }
            if(item.ruleDataType === 'LOCATION_COUNTRY'){
              itemData.push({
                index,
                key: 'code',
                label: 'country'
              });
              services.push(expenseStandardService.getCountry(language.code,isAll))
            }
            if(item.ruleDataType === 'LOCATION_GROUP'){
              itemData.push({
                index,
                key: 'id',
                label: 'levelName'
              });
              services.push(expenseStandardService.getCityGroup(isAll))
            }
            if(item.ruleDataType === 'STRING' && item.dataSource){
              itemData.push({
                index,
                key: 'value',
                label: 'messageKey'
              });
              services.push(expenseStandardService.getCustomEnumerations(item.dataSource))
            }
          }
        });
        Promise.all(services).then(res => {
          itemData.map((item, itemIndex) => {
            let ruleContent = [];
            //睿智设计，excel导入的分隔符是 / ，保存后的是 , ,为啥不能统一？？？
            let ruleContentText = resData.conditions[item.index].ruleContent;
            let sign = ruleContentText.indexOf('/') > -1 ? '/' : ',';
            let values = ruleContentText.split(sign);
            values.map(value => {
              res[itemIndex].data.map(content => {
                if(content[item.key] === value){
                  ruleContent.push(content)
                }
              })
            });
            resData.conditions[item.index].ruleContent = ruleContent;
          });
          if(pullData.length === 0){
            const { expenseTypeSetOfBooks: { id } } = this.props;
            expenseStandardService.getPullData(resData.entityOID, id)
              .then(pullDataRes => {
                this.setState({
                  nowRule: resData,
                  pullData: pullDataRes.data,
                  loading: false,
                  itemData
                }, () => {
                  if (callBack) callBack();
                });
              });
          } else {
            this.setState({
              nowRule: resData,
              loading: false,
              itemData
            }, () => {
              if(callBack) callBack();
            })
          }

        })
      });
    }
  };

  handleClickMenu = (key, rule) => {
    switch(key){
      case 'edit':
        this.setState({ showRuleSlideFrame: true, copy: false, nowEditRule: rule });
        break;
      case 'copy':
        this.setState({ showRuleSlideFrame: true, copy: true, nowEditRule: rule });
        break;
      case 'delete':
        confirm({
          title: messages('setting.key1643')/*确认删除*/,
          content: messages('setting.key1644')/*确认要删除该条规则吗?*/,
          okText:messages('setting.key1100')/*确定*/,
          cancelText: messages('setting.key1080')/*取消*/,
          onOk: () => {
            this.setState({ ruleLoading: true });
            expenseStandardService.deleteRule(rule.ruleOID).then(res => {
              message.success(messages('setting.key213')/*删除成功*/);
              this.getRules(this.getData);
            }).catch(e => {
              this.setState({ ruleLoading: false });
              errorMessage(e.response)
            });
          }
        })
    }
  };

  handleSelectCard = rule => {
    if(rule.ruleOID !== this.state.nowRule.ruleOID){
      this.setState({ nowRule: rule }, () => {
        this.getData();
      })
    }
  };

  renderOperate = (text, record) => {
    const { nowRule } = this.state;
    const { tenantMode } = this.props;
    return (
      nowRule.source === 1001 && !tenantMode
        ? null
        : <section>
          {
            record.ruleDataType !== 'EXPENSE_LEVEL' && [
              <a onClick={() => this.setState({ showSlideFrame: true, nowCondition: record })} key="edit">
                {messages('setting.key1071')/*编辑*/}
              </a>,
              <span className="ant-divider" key="divide"/>
            ]
          }
          <a onClick={() => this.handleDeleteCondition(record)}>{messages('setting.key1101')/*删除*/}</a>
        </section>);
  };

  renderRuleCard = (rule, index) => {
    const { tenantMode } = this.props;
    return (
      <div className="card-container" onClick={e => this.handleSelectCard(rule)} key={rule.ruleOID}>
        <Alert
          className="rule-alert"
          message={<Tooltip title={rule.ruleName} overlayStyle={{ width: 300 }}>{rule.ruleName}</Tooltip>}
          description={
            <div className="rule-content">
              {rule.ruleOID === this.state.nowRule.ruleOID && (
                <Icon type="check-circle" className="selected-icon"/>
              )}
              <If value={rule.source !== 1001 || tenantMode}>
                <Dropdown
                  overlay={(
                    <Menu onClick={e => this.handleClickMenu(e.key, rule)}>
                      <Menu.Item key="edit">
                        <a rel="noopener noreferrer">{messages('setting.key1071')/*编辑*/}</a>
                      </Menu.Item>
                      <Menu.Item key="copy">
                        <a rel="noopener noreferrer">{messages('setting.key1430')/*复制*/}</a>
                      </Menu.Item>
                      <Menu.Item key="delete">
                        <a rel="noopener noreferrer">{messages('setting.key1101')/*删除*/}</a>
                      </Menu.Item>
                    </Menu>
                  )}>
                  <Icon type="bars" className="rule-menu"/>
                </Dropdown>
              </If>
              <div>{messages('setting.key1181')/*币种*/}：{rule.currencyCode}</div>
              <div>{messages('setting.key1096')/*状态*/}：
                <Badge
                  status={rule.enabled ? 'success' : 'error'}
                  text={rule.enabled ? messages('setting.key1086')/*启用*/ : messages('setting.key1087')/*禁用*/}/>
              </div>
              <div>{messages('setting.key2180')/*规则来源*/}：{rule.source === 1001 ? messages('setting.key2181')/*账套级*/ : messages('setting.key2182')/*公司级*/}</div>
            </div>
          }
          type={rule.actionType === 'WARNING' ? 'warning' : 'error'}
          showIcon
        />
      </div>
    );
  };

  getMessageKey = messageKey => {
    const { pullData } = this.state;
    let result = '';
    pullData.map(item => {
      item.messageKey === messageKey && (result = item.name)
    });
    return result;
  };

  renderRuleContent = (ruleContent, record, index) => {
    const { itemData } = this.state;
    let target = ruleContent;
    itemData.map(item => {
      if(item.index === index)
        target = ruleContent.map(content => content[item.label]).join(',');
    });
    if(record.ruleDataType === 'DATETIME'){
      target = moment(ruleContent).format('HH:mm')
    }
    if([1009, 1010].indexOf(record.restriction) > -1){
      target = '-';
    }
    return <Popover placement="topLeft" content={target}>{target}</Popover>;
  };

  handleClose = flag => {
    this.setState({ showSlideFrame: false });
    if(flag){
      this.getData();
    }
  };

  handleDeleteCondition = record => {
    Modal.confirm({
      title: messages('setting.key1538')/*你确定删除吗*/,
      onOk: () => {
        this.setState({ loading: true });
        expenseStandardService.deleteCondition(record.id).then(res => {
          message.success(messages('setting.key213')/*删除成功*/);
          this.getData();
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response)
        })
      }
    });
  };

  handleCloseRule = flag => {
    this.setState({ showRuleSlideFrame: false, copy: false });
    if(flag){
      this.getRules(this.getData)
    }
  };

  handleNewRule = () => {
    this.setState({ showRuleSlideFrame: true, nowEditRule: {} });
  };

  render() {
    const { rules, loading, columns, pullData, showSlideFrame, showRuleSlideFrame,
      copy, nowRule, nowCondition, nowEditRule, ruleLoading } = this.state;
    const { expenseType, tenantMode } = this.props;

    return (
      <div className="expense-type-standard">
          <Spin spinning={ruleLoading}>
            <div className="rule-alert-list">
              <div className="new-rule-card" onClick={this.handleNewRule}>
                <Icon type="plus-circle-o"/>
                <br/> {messages('setting.key1191')/*新增规则*/}
              </div>
              {rules.map(this.renderRuleCard)}
            </div>
          </Spin>
        { nowRule.ruleOID && (
          <div>
            <div style={{ margin: '30px 0 10px 0' }}>
              <If value={nowRule.source !== 1001 || tenantMode}>
                <Button type="primary" onClick={() => this.setState({ showSlideFrame: true, nowCondition: {} })}>
                  <Icon type="plus"/>&nbsp;{messages('setting.key1539')/*新建条件*/}
                </Button>
              </If>
              <Tooltip placement="topLeft" title={messages('setting.key1540')/*每个条件是and关系，需要同时满足*/} arrowPointAtCenter>
                <Icon style={{
                  marginLeft: 10,
                  cursor: 'pointer',
                  fontSize: 16
                }} type="question-circle-o" />
              </Tooltip>
            </div>
            <ResizeTable
              dataSource={nowRule.conditions}
              columns={columns}
              rowKey="id"
              loading={loading}
              defaultExpandAllRows
              rowClassName={record => record.ruleDataType === 'EXPENSE_LEVEL' ? '' : 'row-expand-display-none'}
              expandedRowRender={record => record.ruleDataType === 'EXPENSE_LEVEL' ? messages('setting.key1645')/*注：员工级别不支持变更及新增，建议通过按级别创建人员组后，按申请人组设置校验。*/ : null}/>
          </div>
        )}
        <SlideFrame
          show={showSlideFrame}
          content={NewRule}
          onClose={() => this.setState({ showSlideFrame: false })}
          params={{
            nowRule,
            nowCondition,
            pullData,
            showSlideFrame,
            expenseType,
            expenseTypeOID: expenseType.expenseTypeOID
          }}
          afterClose={this.handleClose}
          title={messages('setting.key1330')/*条件*/}/>

        <SlideFrame
          content={NewExpenseTypeRule}
          show={showRuleSlideFrame}
          onClose={() => this.setState({ showRuleSlideFrame: false })}
          params={{
            nowRule: nowEditRule,
            expenseTypeOID: expenseType.expenseTypeOID,
            copy,
            showSlideFrame: showRuleSlideFrame
          }}
          afterClose={this.handleCloseRule}
          title={messages('setting.key1082')/*规则*/}/>

      </div>
    )
  }
}

ExpenseTypeStandard.propTypes = {
  expenseType: React.PropTypes.object,
  onSave: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenantMode: state.main.tenantMode,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks
  }
}

export default connect(mapStateToProps)(ExpenseTypeStandard)

